<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>数组作业</title>
    <style>
        pre {
            font-size: 20px;
        }
    </style>
</head>

<body>
    <script>
        //1.移除数组arr["西瓜","香蕉","菠萝"]中除西瓜外的所有元素，不要使用第二个数组

        //2.移除数组 arr[1, 2, 3, 4, 2] 中的2。不要直接修改数组 arr，结果返回新的数组

        //3.定义一个函数,能在数组 arr[1, 2, 3, 4, 2] 的 "2"后面添加元素 "jack"。不要直接修改数组 arr，结果返回新的数组

        //4.统计数组 arr[1, 2, 3, 4, 2] 中 2 出现的次数

        //5.定义一个函数，用splice实现数组的去重
    </script>

    <h1>1.</h1>
    <pre>
      var arr = ["西瓜", "香蕉", "菠萝"];
      arr.splice(1);
      console.log(arr);
    </pre>

    <h1>2.</h1>
    <pre>  
      var arr = [1, 2, 3, 4, 2];
      var newarray = [];
      for (var i = 0; i < arr.length; i++) {
          if (arr[i] != 2) {
              newarray.push(arr[i]);
          }

      }
      console.log(newarray);</pre>

    <h1>3.</h1>
    <pre>
        var arr = [1, 2, 3, 4, 2];

        function add(arr, num, str) {
            var newarray = [];
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == num) {
                    newarray.push(arr[i], str);
                } else {
                    newarray.push(arr[i]);
                }
            }
            return newarray;
        }
        console.log(add(arr, 2, 'jack'));
    </pre>

    <h1>4.</h1>
    <pre>
      var arr = [1, 2, 3, 4, 2];
      var second = 0;
      for (var i = 0; i < arr.length; i++) {
          if (arr[i] == 2) {
              second++;
          }
      }
      console.log(second);
    </pre>

    <h1>5.</h1>
    <pre>
      var arr = [1, 2, 2, 2, 1, 23, 1, 3, 78, 99];
      for (var i = 0; i < arr.length; i++) {
          for (var j = i + 1; j < arr.length; j++) {
              if (arr[i] == arr[j]) {
                  arr.splice(j, 1);
                  j--;
              }
          }
      }
      console.log(arr);
    </pre>
</body>

</html>